作業多到懷疑人生,所以就交給手機來算吧
RadioButton是單選式的按鈕。在一個RadioGroup中可以有多個RadioButton,同時只能有一個RadioButton被點選
RadioGroup屬性設置
RadioButton屬性設置
    <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             android:orientation="horizontal"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"
            android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:id="@+id/radioGroup">
        <RadioButton
                android:text="P"
                android:checked="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/btn_p" android:layout_weight="1"/>
        <RadioButton
                android:text="C"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/btn_c" android:layout_weight="1"/>
        <RadioButton
                android:text="H"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/btn_h" android:layout_weight="1"/>
設置一個function計算階乘,輸入一個整數n,回傳n階乘
fun Factorial(n: Int): Int {
    var m = 1
    //i從1開始,每次迴圈加1,直到i=n+1
    for (i in 1 until n + 1) {
        m *= i
    }
    return m
}
設置計算P、C、H三個公式的function
fun P(i: Int, j: Int) = Factorial(i) / Factorial(i - j)
fun C(i: Int, j: Int) = P(i, j) / Factorial(j)
fun H(i: Int, j: Int) = C(i + j - 1, j)
設置一個function,檢查EditText的輸入是否符合規則,並輸出結果
fun f(m:Int){
    //當輸入不為空時執行
    if(editText1.length()!=0 && editText2.length()!=0 ) {
        var i =editText1.text.toString().toInt()
        var j =editText2.text.toString().toInt()
        
        if(i>j && m!=2){
            when(m){
                0-> tv_out.text="${P(i,j)}"
                else-> tv_out.text="${C(i,j)}"
            }
        }
        if(i+j-1>j && m==2){
            tv_out.text="${H(i,j)}"
        }
    }
    else{
        tv_out.text=""
    }
}
OnCheckedChangeListener
RadioGroup專用的監聽事件,當被監聽的RadioGroup中點選的元件改變時觸發
第一個參數是被監聽的RadioGroup,第二個參數是被點選的RadioButton的ID
radioGroup.setOnCheckedChangeListener { radioGroup, i ->
}
辨認選定元件的方式有兩種:
//使用.isChecked 可以得到RadioButton的選定狀態
if(btn_p.isChecked){
    mode = 0
    textView.text = "P"
}
else if(btn_p.isChecked){
    mode = 1
    textView.text = "C"
}
else{
    mode = 2
    textView.text = "H"
}
//.id 可以得到RadioButton的id
if(i == btn_p.id){
    mode = 0
    textView.text = "P"
}
else if(i == btn_c.id){
    mode = 1
    textView.text = "C"
}
else(i == btn_h.id){
    mode = 2
    textView.text = "H"
}
